//
// Created by xiongqimin on 2022/3/24.
//

#ifndef WAP_FILEPLAYINGSOURCE_H
#define WAP_FILEPLAYINGSOURCE_H

#include "api/audio/audio_mixer.h"
#include "rtc_base/strings/string_builder.h"
#include "common_audio/wav_file.h"

namespace webrtc {
namespace test {

class FilePlayingSource : public AudioMixer::Source {
public:
    explicit FilePlayingSource(std::string filename)
            : wav_reader_(new WavReader(filename)),
              sample_rate_hz_(/*wav_reader_->sample_rate()*/8000),
              samples_per_channel_(sample_rate_hz_ / 100),
              number_of_channels_(wav_reader_->num_channels()) {}

    AudioFrameInfo GetAudioFrameWithInfo(int target_rate_hz,
                                         AudioFrame* frame) override {
        frame->samples_per_channel_ = samples_per_channel_;
        frame->num_channels_ = number_of_channels_;
        frame->sample_rate_hz_ = target_rate_hz;

        RTC_CHECK_EQ(target_rate_hz, sample_rate_hz_);

        const size_t num_to_read = number_of_channels_ * samples_per_channel_;
        const size_t num_read =
                wav_reader_->ReadSamples(num_to_read, frame->mutable_data());

        file_has_ended_ = num_to_read != num_read;
        if (file_has_ended_) {
            frame->Mute();
        }
        return file_has_ended_ ? AudioFrameInfo::kMuted : AudioFrameInfo::kNormal;
    }

    int Ssrc() const override { return 0; }

    int PreferredSampleRate() const override { return sample_rate_hz_; }

    bool FileHasEnded() const { return file_has_ended_; }

    std::string ToString() const {
        rtc::StringBuilder ss;
        ss << "{rate: " << sample_rate_hz_ << ", channels: " << number_of_channels_
           << ", samples_tot: " << wav_reader_->num_samples() << "}";
        return ss.Release();
    }

private:
    std::unique_ptr<WavReader> wav_reader_;
    int sample_rate_hz_;
    int samples_per_channel_;
    int number_of_channels_;
    bool file_has_ended_ = false;
};
}  // namespace test
}  // namespace webrtc
#endif //WAP_FILEPLAYINGSOURCE_H
